import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_smart_dialog/flutter_smart_dialog.dart';
import 'package:get/get.dart';
import 'package:sptapp/basic/base_info.dart';
import 'package:sptapp/config/const.dart';
import 'package:sptapp/moudle/common_info.dart';
import 'package:sptapp/routes/route.dart';
import 'package:sptapp/utils/string_tool.dart';

import '../../api/interface/user_api.dart';
import '../../api/request/response_data.dart';
import '../../moudle/message.dart';
import '../../widget/common_widget.dart';

class MinSelectDeviceDialog extends StatefulWidget {
  final Function callBack;
  const MinSelectDeviceDialog({super.key, required this.callBack});

  @override
  State<MinSelectDeviceDialog> createState() => _MinSelectDeviceDialogState();
}

class _MinSelectDeviceDialogState extends State<MinSelectDeviceDialog> {

  int selectIndex = 0;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    if(baseDevices.isNotEmpty){
      for(var item in baseDevices){
        if(baseDeviceNum != null){
          if(item['sn'] == baseDeviceNum){
            selectIndex = baseDevices.indexOf(item);
          }
        }
      }
    }
  }

  _deleteDevice(item)async{
    Map<String,dynamic> data = {
      'id': item['id']
    };
    showLoading();
    ResponseData res = await UserAPI.deleteDevice(data);
    hideLoading();
    if(res.code == 200){
      selectIndex = 0;
      getDevicesList((){
        if(mounted){setState(() {
          if(baseDevices.isNotEmpty){
            for(var item in baseDevices){
              if(baseDeviceNum != null){
                if(item['sn'] == baseDeviceNum){
                  selectIndex = baseDevices.indexOf(item);
                }
              }
            }
            if(baseDevices[selectIndex]['sn'].toString() != baseDeviceNum){
              LocalBaseInfo.setDeviceNum(baseDevices[selectIndex]['sn']);
              baseDeviceNum = baseDevices[selectIndex]['sn'];
              baseDevice = baseDevices[selectIndex];
              if(widget.callBack!=null){
                widget.callBack();
              }
            }
          }else{
            if(widget.callBack!=null){
              widget.callBack();
            }
            Navigator.of(context).pop();
          }
        });}
      });
    }
    if(mounted){setState(() {});}
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.only(left: 48.w,right: 48.w,top: 32.w,bottom: ScreenUtil().bottomBarHeight+48.w),
      decoration: BoxDecoration(
          color: Color(0xff1E1E1E),
        borderRadius: BorderRadius.only(topLeft: Radius.circular(32.w),topRight: Radius.circular(32.w))
      ),
      child: Column(
        mainAxisSize: MainAxisSize.min,
        children: [
          Container(
            child: Row(
              children: [
                Text(min_device_select_dialog_text.tr,style: TextStyle(
                    color: Colors.white,
                    fontSize: 28.sp,
                    fontWeight: FontWeight.w600
                ),),
                GestureDetector(
                  onTap: (){
                    SmartDialog.dismiss();
                    Navigator.of(context).pop();
                  },
                  child: Icon(Icons.close,size: 30.sp,color: Color(0xff999999),),
                )
              ],
              mainAxisAlignment: MainAxisAlignment.spaceBetween,
            ),
          ),
          SizedBox(height: 50.h,),
          Container(
            height: 380.w,
            child: ListView.builder(itemBuilder: (ctx,index){
              return GestureDetector(
                onTap: (){
                  setState(() {
                    selectIndex = index;
                  });

                },
                child: Container(
                  height: 380.w,
                  // width: 160.w,
                  alignment: Alignment.center,
                  margin: EdgeInsets.only(right: 50.w),
                  child: Column(
                    children: [
                      Image.asset('assets/home/min_spt.png',width: 150.w,),
                      Container(
                        padding: EdgeInsets.symmetric(horizontal: 6.w),
                        child: Text(baseDevices[index]['name']??'',style: TextStyle(
                            color: selectIndex == index? Colors.white:Color(0x5fffffff),
                            fontSize: 32.sp,
                            fontWeight: FontWeight.w600
                        ),),
                      ),
                      SizedBox(height: 16.h,),
                      Visibility(child: GestureDetector(
                        onTap: (){
                          StringTool.long_p('device == '+baseDevices[index].toString());
                          Navigator.of(MyRoute.navigatorKey.currentContext!).pushNamed('MinChangeDeviceName', arguments: baseDevices[index]).then((val){
                            if(val is String && val!=null && val.isNotEmpty){
                              baseDevices[index]['name'] = val;
                            }
                            if(mounted){setState(() {});}
                          });
                        },
                        child: Container(
                          width: 140.w,
                          height: 40.w,
                          alignment: Alignment.center,
                          decoration: BoxDecoration(
                              color: Color(0xff313131),
                              borderRadius: BorderRadius.circular(40.w)
                          ),
                          child: Text('Rename',style: TextStyle(
                              color: Colors.white,
                              fontSize: 20.sp
                          ),),
                        ),
                      ),visible: selectIndex == index,)
                    ],
                  ),
                ),
              );
            },padding: EdgeInsets.zero,itemCount: baseDevices.length,scrollDirection: Axis.horizontal,),
          ),
          SizedBox(height: 50.h,),
          GestureDetector(
            onTap: (){
              if(baseDeviceNum != baseDevices[selectIndex]['sn']){
                LocalBaseInfo.setDeviceNum(baseDevices[selectIndex]['sn']);
                baseDeviceNum = baseDevices[selectIndex]['sn'];
                baseDevice = baseDevices[selectIndex];
                SmartDialog.dismiss().then((val){
                  if(widget.callBack!=null){
                    widget.callBack();
                  }
                  showToast('Device has been switched');
                  Navigator.of(context).pop();
                });
              }
            },
            child: Container(
              child: Text(bottom_alert_sure_btn.tr,style: TextStyle(
                  color: Colors.white,
                  fontSize: 28.sp
              ),),
              decoration: BoxDecoration(
                  color: baseDevices.isNotEmpty && baseDeviceNum != baseDevices[selectIndex]['sn'] ? themeColor:themeDisableColor,
                  borderRadius: BorderRadius.circular(8.w)
              ),
              height: 84.w,
              alignment: Alignment.center,
            ),
          ),
          Visibility(visible: baseDevices.isNotEmpty,child: Column(
            children: [
              SizedBox(height: 24.h,),
              GestureDetector(
                onTap: (){
                  _deleteDevice(baseDevices[selectIndex]);
                },
                child: Container(
                  child: Text(add_device_page_remove_title.tr,style: TextStyle(
                      color: Color(0xffFF5353),
                      fontSize: 28.sp
                  ),),
                  decoration: BoxDecoration(
                      border: Border.all(color: Color(0xff6B6B6B),width: 1.w),
                      borderRadius: BorderRadius.circular(8.w)
                  ),
                  height: 84.w,
                  alignment: Alignment.center,
                ),
              )
            ],
          ),)
        ],
      ),
    );
  }
}
